<?php
	//$_GET['sec']= 8;
	function zeroEsquerda($string){
		$size = strlen($str);
		switch($size){
			case 1: $string = '0000'.$string; break;
			case 2: $string = '000'.$string; break;
			case 3: $string = '00'.$string; break;
			case 4: $string = '0'.$string; break;
		}
		return $string;
	}


	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * Easy set variables
	 */
	
	/* Array of database columns which should be read and sent back to DataTables. Use a space where
	 * you want to insert a non-database field (for example a counter or static image)
	 */
	$aColumns = array('numero_protocolo','ano', 'credor', 'valor','nome_secretaria','status' );

	
	/* Indexed column (used for fast and accurate table cardinality) */
	$sIndexColumn = "numero_protocolo";
	
	/* DB table to use */
	$sTable = "protocolo_empenho";
	$sTable2 = ", secretaria, status";
	
	/*CONECTA BANCO*/
	include("conexao_banco.php");
	
	
	
	/* 
	 * Paging
	 */
	$sLimit = "";
	if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
	{
		$sLimit = "LIMIT ".mysql_real_escape_string( $_GET['iDisplayStart'] ).", ".
			mysql_real_escape_string( $_GET['iDisplayLength'] );
	}
	
	
	/*
	 * Ordering
	 */
	$sOrder = "";
	if ( isset( $_GET['iSortCol_0'] ) )
	{
		$sOrder = "ORDER BY  ";
		for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
		{
			if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
			{
				$sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
				 	".mysql_real_escape_string( $_GET['sSortDir_'.$i] ) .", ";
			}
		}
		
		$sOrder = substr_replace( $sOrder, "", -2 );
		if ( $sOrder == "ORDER BY" )
		{
			$sOrder = "";
		}
	}
/*	else{
		$sOrder = "ORDER BY `protocolo_empenho`.`ano` DESC,  `protocolo_empenho`.`numero_protocolo` DESC";

	}
*/	
	
	/* 
	 * Filtering
	 * NOTE this does not match the built-in DataTables filtering which does it
	 * word by word on any field. It's possible to do here, but concerned about efficiency
	 * on very large tables, and MySQL's regex functionality is very limited
	 */
	$sWhere = "";
	$sWhere2 = "";

	if ( isset($_GET['sSearch']) && $_GET['sSearch'] != "" )
	{
		$sWhere = "WHERE (";
		for ( $i=0 ; $i<count($aColumns) ; $i++ )
		{
			$sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string( $_GET['sSearch'] )."%' OR ";
		}
		$sWhere = substr_replace( $sWhere, "", -3 );
		$sWhere .= ')';
		$sWhere2 = " AND secretaria_idSecretaria = idSecretaria AND status_idstatus=idstatus AND secretaria_idSecretaria=".$_GET['sec'];
	}else
		$sWhere2 = " WHERE secretaria_idSecretaria = idSecretaria AND status_idstatus=idstatus AND secretaria_idSecretaria=".$_GET['sec'];
	

	/* Individual column filtering */
	for ( $i=0 ; $i<count($aColumns) ; $i++ )
	{
		if($i > 1){
			if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
			{
				if ( $sWhere == "" )
				{
					$sWhere = "WHERE ";
					$sWhere2 = " AND secretaria_idSecretaria = idSecretaria AND status_idstatus=idstatus AND secretaria_idSecretaria=".$_GET['sec'];
				}
				else
				{
					$sWhere .= " AND ";
					$sWhere2 = " AND secretaria_idSecretaria = idSecretaria AND status_idstatus=idstatus AND secretaria_idSecretaria=".$_GET['sec'];
				}
				$sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string($_GET['sSearch_'.$i])."%' ";
			}
		}else{
		if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
			{
				if ( $sWhere == "" )
				{
					$sWhere = "WHERE ";
					$sWhere2 = " AND secretaria_idSecretaria = idSecretaria AND status_idstatus=idstatus AND secretaria_idSecretaria=".$_GET['sec'];
				}
				else
				{
					$sWhere .= " AND ";
					$sWhere2 = " AND secretaria_idSecretaria = idSecretaria AND status_idstatus=idstatus AND secretaria_idSecretaria=".$_GET['sec'];
				}
				$sWhere .= $aColumns[$i]." LIKE '".mysql_real_escape_string($_GET['sSearch_'.$i])."' ";
			}
		
		
		}
	}
	
	
	/*
	 * SQL queries
	 * Get data to display
	 */
	//$test =" WHERE secretaria_idSecretaria= idSecretaria AND status_idstatus=idstatus";
	
	mysql_query("SET NAMES 'utf8'"); // mostrar nomes com acentos

	$sQuery = "SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns))." FROM
		$sTable
		$sTable2
		$sWhere
		$sWhere2
		$sOrder
		$sLimit";

//	echo $sQuery;
	$rResult = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
	
	/* Data set length after filtering */
	$sQuery = "
		SELECT FOUND_ROWS()
	";
	$rResultFilterTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
	$aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
	$iFilteredTotal = $aResultFilterTotal[0];
	
	/* Total data set length */
	$sQuery = "
		SELECT COUNT(".$sIndexColumn.")
		FROM   $sTable
	";
	$rResultTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
	$aResultTotal = mysql_fetch_array($rResultTotal);
	$iTotal = $aResultTotal[0];
	
	
	/*
	 * Output
	 */
	$output = array(
		"sEcho" => intval($_GET['sEcho']),
		"iTotalRecords" => $iTotal,
		"iTotalDisplayRecords" => $iFilteredTotal,
		"aaData" => array()
	);
	
	while ( $aRow = mysql_fetch_array($rResult))
	{
		$row = array();
		for ( $i=0 ; $i < count($aColumns) ; $i++ )
		{
		/*	if($i == 0){
				$proto = zeroEsquerda($aRow[$aColumns[$i]]);
				
			}elseif($i == 1){
				$proto = $proto.'/'.$aRow[$aColumns[$i]];
				$row[] = $proto;
			}else{*/
				$row[] = $aRow[$aColumns[$i]];
		//	}
		}

		$row[] = "<a href=view_empenho.php?id=".$aRow[0]."&ano=".$aRow[1].">Consultar</a>";



		$output['aaData'][] = $row;
	}
	
	echo json_encode( $output );
?>
